<template>
  <div class="online-work-order-form">
    <van-nav-bar class="header"
      left-arrow
      @click-left="onBack()"
    >
      <template #title>
        <p style="font-size: 16px;color: #333333;font-weight: 400;">{{form.formName}}</p>
      </template>
      <template #left>
        <van-icon name="arrow-left" size="18" color="#3B3938" />
      </template>
      <template #right>
        <van-icon name="plus" size="18" color="#6C6C6C" @click="onStartFlow()" />
      </template>
    </van-nav-bar>
    <online-filter-box
      :supportSort="false"
      :supportFilter="true"
      style="background: white; padding: 5px 18px;"
      @refresh="onRefresh"
      @reset="onReset"
    >
      <van-search slot="filter" style="padding: 0px; flex-grow: 1;"
        v-model="formFilter.workOrderCode"
        placeholder="请输入工单编码"
        @search="onRefresh"
        left-icon=""
      >
        <div slot="left" class="search-label">
          <van-dropdown-menu active-color="#ff7700">
            <van-dropdown-item v-model="formFilter.flowStatus" :options="flowStatusDropdownList" @change="deopdownChange()">
              <template #title>
                <div style="display:flex;justify-content: flex-end;">
                  <span>{{ SysFlowWorkOrderStatus.getValue(formFilter.flowStatus) || '全部' }}</span>
                </div>
              </template>
            </van-dropdown-item>
          </van-dropdown-menu>
          <p class="line"></p>
        </div>
        <template #right-icon>
          <i class="mobile-font icon-search"></i>
        </template>
      </van-search>
      <!-- 过滤字段 -->
      <online-custom-block subWidgetClass="filter-item"
        :widgetList="filterWidgetList"
      />
    </online-filter-box>
    <!--
    <van-row class="filter-box" type="flex" align="center">
      <van-search style="padding: 0px;flex-grow: 1;"
        v-model="formFilter.workOrderCode"
        placeholder="请输入工单编码"
        @search="onRefresh"
        left-icon=""
      >
        <div slot="left" class="search-label">
          <van-dropdown-menu active-color="#ff7700">
            <van-dropdown-item v-model="formFilter.flowStatus" :options="flowStatusDropdownList" @change="deopdownChange()">
              <template #title>
                <div style="display:flex;justify-content: flex-end;">
                  <span>{{ SysFlowWorkOrderStatus.getValue(formFilter.flowStatus) || '全部' }}</span>
                </div>
              </template>
            </van-dropdown-item>
          </van-dropdown-menu>
          <p class="line"></p>
        </div>
        <template #right-icon>
          <i class="mobile-font icon-search"></i>
        </template>
      </van-search>
    </van-row>
    -->
    <CustomList v-if="isReady" ref="cardList" style="padding: 16px 16px 0px 16px; flex-grow: 1;"
      :loadData="loadTableData"
    >
      <TaskCard class="card-item" slot-scope="scope"
        :cardData="getCardData(scope.data)"
        :flowStatus="scope.data.flowStatus"
        :finishedWithAgree="scope.data.finishedWithAgree"
      >
        <van-row slot="menu" class="menu-box" type="flex" justify="end" align="center">
          <van-button class="menu-btn" type="danger" size="small" plain
            :disabled="scope.data.flowStatus === SysFlowWorkOrderStatus.CANCEL"
            @click.stop="onCancelWorkOrder(scope.data)"
          >
            撤销
          </van-button>
          <van-button class="menu-btn" type="primary" size="small" color="#07C160" plain
            :disabled="scope.data.flowStatus === SysFlowWorkOrderStatus.CANCEL"
            @click.stop="onHandlerRemindClick(scope.data)"
          >
            催办
          </van-button>
          <van-button class="menu-btn" type="default" size="small"
            v-if="getPrintOperation != null"
            :class="getPrintOperation.btnClass"
            @click.stop="onPrint(getPrintOperation, scope.data)"
          >
            {{getPrintOperation.name || '打印'}}
          </van-button>
          <van-button class="menu-btn" type="primary" size="small"
            v-if="(scope.data.initTaskInfo || {}).taskKey !== (scope.data.runtimeTaskInfo || {}).taskKey"
            @click.stop="onViewWorkOrder(scope.data)"
          >
            详情
          </van-button>
          <van-button class="menu-btn" type="primary" size="small"
            v-if="(scope.data.initTaskInfo || {}).taskKey === (scope.data.runtimeTaskInfo || {}).taskKey"
            @click.stop="onHandlerWorkOrder(scope.data)"
          >
            办理
          </van-button>
        </van-row>
      </TaskCard>
    </CustomList>
  </div>
</template>

<script>
import { Notify } from 'vant';
import { findItemFromList } from '@/utils';
import CustomList from '@/components/CustomList.vue';
import TaskCard from '@/views/workflow/components/taskCard.vue';
import { OnlineFormMixins } from './onlineFormMixins.js';
import { FlowOperationController, FlowEntryController } from '@/api/flowController.js';

export default {
  name: 'OnlineWorkOrderForm',
  props: {
    entryId: {
      type: String
    },
    formConfig: {
      type: Object,
      required: true
    }
  },
  mixins: [OnlineFormMixins],
  components: {
    CustomList,
    TaskCard
  },
  provide () {
    return {
      form: () => {
        return {
          ...this.form,
          getWidgetValue: this.getWidgetValue,
          getWidgetVisible: this.getWidgetVisible
          /*
          ...this.form,
          readOnly: this.dialogParams.readOnly,
          getWidgetValue: this.getWidgetValue,
          getWidgetProp: this.getWidgetProp,
          getWidgetVisible: this.getWidgetVisible,
          onValueChange: this.onValueChange,
          onWidgetValueChange: this.onWidgetValueChange,
          getDropdownParams: this.getDropdownParams,
          checkOperationPermCode: this.checkOperationPermCode,
          checkOperationDisabled: this.checkOperationDisabled,
          checkOperationVisible: this.checkOperationVisible,
          cloneWidget: this.cloneWidget,
          handlerOperation: this.handlerOperation,
          getDictDataList: this.getDictDataList,
          loadOnlineFormConfig: this.loadOnlineFormConfig,
          getWidgetObject: widgetData.getWidgetObject
          */
        }
      }
    }
  },
  data () {
    return {
      isReady: false,
      showStatusFilter: false,
      processDefinitionKey: undefined,
      processDefinitionName: undefined,
      formFilter: {
        workOrderCode: undefined,
        flowStatus: undefined
      }
    }
  },
  methods: {
    onBack () {
      this.$router.replace({
        name: 'home'
      });
    },
    onRefresh () {
      if (this.$refs.cardList) this.$refs.cardList.reset();
    },
    onReset () {
      if (Array.isArray(this.filterWidgetList)) {
        this.filterWidgetList.forEach(widget => {
          this.onValueChange(widget, undefined);
        });
        this.formFilter = {
          workOrderCode: undefined,
          flowStatus: undefined
        }
        this.onRefresh();
      }
    },
    deopdownChange () {
      this.onRefresh();
    },
    getCardData (cardData) {
      return {
        title: cardData.processDefinitionName,
        subTitle: [
          '工单编号：' + cardData.workOrderCode || '无',
          '发起人：' + cardData.userShowName || '无',
          '当前任务：' + ((cardData.runtimeTaskInfo || {}).taskName || '无'),
          '创建日期：' + cardData.createTime || '无'
        ]
      }
    },
    async loadTableData (pageNum) {
      try {
        let params = {
          pageParam: {
            pageNum: pageNum,
            pageSize: 20,
            count: false
          },
          filterDtoList: this.getQueryParams(this.filterWidgetList),
          flowWorkOrderDtoFilter: {
            flowStatus: this.formFilter.flowStatus,
            workOrderCode: this.formFilter.workOrderCode
          }
        }
        // 脱敏设置
        params.ignoreMaskFields = this.getIgnoreMaskFields();
        if (typeof this.queryTable.eventInfo[this.OnlineFormEventType.BEFORE_LOAD_TABLE_DATA] === 'function') {
          params = await this.queryTable.eventInfo[this.OnlineFormEventType.BEFORE_LOAD_TABLE_DATA](params);
        }
        if (params == null) {
          throw new Error('取消加载数据');
        }

        let res = await FlowOperationController.listWorkOrder(this, params, {
          processDefinitionKey: this.processDefinitionKey
        });

        res.data.dataList = res.data.dataList.map(item => {
          let initTaskInfo = item.initTaskInfo == null ? {} : JSON.parse(item.initTaskInfo);
          let runtimeTaskInfo = (Array.isArray(item.runtimeTaskInfoList) && item.runtimeTaskInfoList.length > 0) ? item.runtimeTaskInfoList[0] : {};
          return {
            ...item,
            flowStatusShowName: this.SysFlowWorkOrderStatus.getValue(item.flowStatus),
            initTaskInfo,
            runtimeTaskInfo
          }
        });
        if (typeof this.queryTable.eventInfo[this.OnlineFormEventType.AFTER_LOAD_TABLE_DATA] === 'function') {
          res.data.dataList = await this.queryTable.eventInfo[this.OnlineFormEventType.AFTER_LOAD_TABLE_DATA](res.data.dataList);
        }
        return {
          dataList: res.data.dataList,
          totalCount: res.data.totalCount
        };
      } catch (e) {
        console.log(e);
        throw e;
      }
    },
    onStartFlow () {
      if (this.processDefinitionKey == null) return;
      let params = {
        processDefinitionKey: this.processDefinitionKey
      }
      FlowOperationController.viewInitialTaskInfo(this, params).then(res => {
        if (res.data && res.data.taskType === this.SysFlowTaskType.USER_TASK && res.data.assignedMe) {
          this.$router.push({
            name: res.data.routerName || 'handlerFlowTask',
            query: {
              processDefinitionKey: this.processDefinitionKey,
              formId: res.data.formId,
              routerName: res.data.routerName,
              readOnly: res.data.readOnly,
              taskName: '启动流程',
              isDraft: true,
              flowEntryName: this.processDefinitionName,
              operationList: (res.data.operationList || []).filter(item => {
                return item.type !== this.SysFlowTaskOperationType.CO_SIGN && item.type !== this.SysFlowTaskOperationType.REVOKE && item.type !== this.SysFlowTaskOperationType.SIGN_REDUCTION;
              }),
              variableList: res.data.variableList
            }
          });
        } else {
          FlowOperationController.startOnly(this, {
            processDefinitionKey: this.processDefinitionKey
          }).then(res => {
            Notify({ type: 'success', message: '启动成功！' });
          }).catch(e => {});
        }
      }).catch(e => {});
    },
    onHandlerWorkOrder (row) {
      if (this.processDefinitionKey == null) return;
      let taskId = (Array.isArray(row.runtimeTaskInfoList) && row.runtimeTaskInfoList.length > 0) ? row.runtimeTaskInfoList[0].taskId : undefined;
      let params = {
        processInstanceId: row.processInstanceId,
        processDefinitionId: row.processDefinitionId,
        taskId: taskId
      }
      FlowOperationController.viewRuntimeTaskInfo(this, params).then(res => {
        if (res.data) {
          this.$router.push({
            name: res.data.routerName || 'handlerFlowTask',
            query: {
              isRuntime: true,
              isDraft: row.flowStatus === this.SysFlowWorkOrderStatus.DRAFT,
              flowStatus: row.flowStatus,
              taskId: taskId,
              processDefinitionKey: row.processDefinitionKey,
              processInstanceId: row.processInstanceId,
              processDefinitionId: row.processDefinitionId,
              formId: res.data.formId,
              routerName: res.data.routerName,
              readOnly: res.data.readOnly,
              taskName: (row.runtimeInitialTask || {}).taskName,
              flowEntryName: row.processDefinitionName,
              processInstanceInitiator: row.processInstanceInitiator,
              operationList: (res.data.operationList || []).filter(item => item.type !== this.SysFlowTaskOperationType.CO_SIGN),
              variableList: res.data.variableList
            }
          });
        }
      }).catch(e => {});
    },
    onViewWorkOrder (row) {
      if (this.processDefinitionKey == null) return;
      let params = {
        processInstanceId: row.processInstanceId
      }
      FlowOperationController.viewInitialHistoricTaskInfo(this, params).then(res => {
        if (res.data) {
          this.$router.push({
            name: res.data.routerName || 'handlerFlowTask',
            query: {
              isRuntime: false,
              flowStatus: row.flowStatus,
              processDefinitionKey: row.processDefinitionKey,
              processInstanceId: row.processInstanceId,
              processDefinitionId: row.processDefinitionId,
              formId: res.data.formId,
              routerName: res.data.routerName,
              readOnly: true,
              taskId: row.runtimeTaskInfo.taskId,
              taskName: row.runtimeTaskInfo.taskName,
              flowEntryName: row.processDefinitionName,
              processInstanceInitiator: row.userShowName
            }
          });
        }
      }).catch(e => {});
    },
    onHandlerRemindClick (row) {
      FlowOperationController.remindRuntimeTask(this, {
        workOrderId: row.workOrderId
      }).then(res => {
        Notify({ type: 'success', message: '催办成功！' });
      }).catch(e => {});
    },
    onCancelWorkOrder (row) {
      this.$dialog.confirm({
        title: '消息',
        message: '是否撤销此工单？'
      }).then(res => {
        let params = {
          workOrderId: row.workOrderId,
          cancelReason: '主动撤销'
        }

        FlowOperationController.cancelWorkOrder(this, params).then(res => {
          Notify({ type: 'success', message: '撤销成功！' });
          this.onSearch();
        }).catch(e => {});
      }).catch(e => {});
    }
  },
  computed: {
    form () {
      let temp = this.buildFormConfig(this.formConfig);
      return temp;
    },
    queryTable () {
      return this.form.tableWidget;
    },
    filterWidgetList () {
      return this.queryTable.childWidgetList.slice(1);
    },
    getPrintOperation () {
      let operation = findItemFromList(this.form.operationList, this.SysCustomWidgetOperationType.PRINT, 'type');
      return (operation && operation.enabled) ? operation : null;
    },
    getFilterStatusName () {
      return this.SysFlowWorkOrderStatus.getValue(this.formFilter.flowStatus) || '全部';
    },
    flowStatusDropdownList () {
      let tempList = this.SysFlowWorkOrderStatus.getList().map(item => {
        return {
          ...item,
          text: item.name,
          value: item.id
        }
      });
      tempList.unshift({
        id: undefined,
        text: '全部',
        value: undefined
      });
      return tempList;
    }
  },
  mounted () {
    this.isReady = false;
    this.initPage();
    this.initFormWidgetList();
    if (this.entryId) {
      FlowEntryController.viewDict(this, {
        entryId: this.entryId
      }).then(res => {
        this.processDefinitionKey = res.data.processDefinitionKey;
        this.processDefinitionName = res.data.processDefinitionName;
        this.isReady = true;
      }).catch(e => {
        console.log(e);
      });
    } else {
      this.isReady = true;
    }
  }
}
</script>

<style scoped>
.search-label{
  height: 34px;
  width: 85px;
  background: #F7F8FA;
  /* border-right: 2px solid #ff7700; */
  display: flex;
  flex-direction: row;
  /* position: relative; */
}
.search-label .line{
  height: 20px;
  width: 0;
  margin: auto 0px auto 0;
  border-right: 1px solid #d9dbde;
  z-index: 999;
  /* position: absolute;
  top: 7px;
  right: 5px; */
}
  .card-item + .card-item {
    margin-top: 16px;
  }
  .online-work-order-form {
    height: 100vh;
    display: flex;
    flex-direction: column;
    background: #F6F7F9;
  }

  .menu-box {
    border-top: 1px solid #E8E8E8;
    padding-top: 8px;
    margin-top: 10px;
  }
  .menu-btn {
    width: 64px;
    border-radius: 4px;
  }
  .menu-btn + .menu-btn {
    margin-left: 8px;
  }

  .filter-box {
    min-height: 40px;
    background: white;
    padding: 5px 16px;
  }
</style>
<style>
.van-dropdown-menu{
  height: 34px;
  background: #F7F8FA;
}
.van-dropdown-menu__item{
  height: 34px;
  width: 85px;
  background: #F7F8FA;
  justify-content: space-around !important;
}
.van-dropdown-menu__bar{
  height: 34px !important;
  background: #F7F8FA;
  box-shadow: none !important;
}
.van-dropdown-menu__title{
  line-height: 34px;
  background: #F7F8FA;
  color: #000000;
  border: none;
}
.van-dropdown-item__option{
  padding: 10px 20px !important;
}
.van-dropdown-menu__title::after{
  right: -5px !important;
  margin-top: -6px !important;
  border: 4px solid !important;
  border-color: transparent transparent #17191c #17191c !important;
}
.van-dropdown-menu__title--active::after{
  border-color: transparent transparent #ff7700 #ff7700 !important;
}
</style>
